<?php
/**
 * MageApi
 *
 * NOTICE OF LICENSE
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * @category    MageApi
 * @package     MageApi_Connector
 * @copyright   Copyright (c) 2011 Tomas Krejci (tomas789@gmail.com)
 * @license     http://www.opensource.org/licenses/mit-license.php  The MIT License (MIT)
 */

class MageApi_Connector
{
	/*
	 * Server IP address or hostname
	 * @var string server address
	 */
	private $_apiServer;
	
	/*
	 * API username
	 * @var string API username
	 */
	private $_apiUser;
	
	/*
	 * API password
	 * @var string API password
	 */
	private $_apiPasswd;
	
	private $_proxy;
	
	private $_sessionId;
	
	/**
	 * List of predefined constants
	 * @var array available connection constants
	 */
	private $_constants = array(
		'MAGEAPI_HOST',
		'MAGEAPI_USER',
		'MAGEAPI_PASSWORD'
	);
	
	public function __construct() {
		$params = @func_get_arg(0);
		
		if(is_array($params)) {
			$this->setParams($params);
			
			if($params['connect']) {
				$this->_connect();
			}
		}
		
		foreach($this->_constants as $constant) {
			if(defined($constant)) {
				$this->setParam(
					str_replace('MAGEAPI_', '', $constant), 
					constant($constant)
				);
			}
		}
	}
	
	public function __destruct() {
		$this->_disconnect();
	}
	
	private function _connect() {
		try {
			$this->_proxy = new SoapClient(
				'http://' . $this->_apiServer . '/index.php/api/soap/?wsdl');
			
			$this->_sessionId = $this->_proxy->login(
				$this->_apiUser, 
				$this->_apiPasswd
			);
			
		} catch(MageApi_Exception $e) {
			echo "Caught exception: " . get_class($e) . "\n";
    		echo "Message: " . $e->getMessage() . "\n";
		}
		
	}
	
	private function _disconnect() {
		if($this->_proxy)
			$this->_proxy->call('endSession', $this->_sessionId);
		
		$this->_sessionId = NULL;
		$this->_proxy     = NULL;
	}
	
	/**
	 * Set multiple parameters using MageApi::setParam()
	 * @param array array of parameters
	 * @throws Exception
	 */
	public function setParams(array $params) {
		if(!is_array($params))
			throw new Exception('Function ' . __CLASS__ . '::' . __FUNCTION__ . '()' .
			' expects parameter 1 to be array');
			
		foreach($params as $paramName => $paramValue) {
			if('connect' != $paramName)
				$this->setParam($paramName, $paramValue);
		}
		
		/* Connect must be last one */
		if(array_key_exists('connect', $params))
			$this->setParam('connect', true);
	}
	
	/**
	 * Set 1 configuration parameter
	 * @param string name of parameter (host|user|password)
	 * @param string value of parameter
	 * @throws Exception
	 */
	public function setParam(string $paramName, string $paramValue) {
		if(!is_string(func_get_arg(0)) || !is_string(func_get_arg(1)))
			throw new Exception('Function ' . __CLASS__ . '::' . __FUNCTION__ . '()' .
			' expects both parameters to be string');
		
		switch($paramName) {
			case 'host':
				$this->_apiServer = $paramValue;
				break;
			case 'user':
				$this->_apiUser = $paramValue;
				break;
			case 'password':
				$this->_apiPasswd = $paramValue;
				break;
			case 'connect':
				if($paramValue) $this->_connect();
				else $this->_disconnect();
			default:
				throw new Exception('Function ' . __CLASS__ . '::' . __FUNCTION__ . '()' .
				' unexpected parameter');
				break;
		}
	}
	
	/**
	 * Return array of parameters
	 * @return array array of parameters
	 */
	function getParams() {
		return array(
			'host'     => $this->_apiServer,
			'user'     => $this->_apiUser,
			'password' => $this->_apiPasswd
		);
	}
}
